package mc.contents.web.servlet;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.taobao.api.domain.Item;
import mc.contents.pojo.view.RankItem;
import mc.contents.web.common.AbstractResponseHttpServlet;
import mc.contents.web.common.CrawRequest;
import mc.contents.web.common.CrawResult;
import mc.contents.web.result.RankCrawResult;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by LuoHui on 14-11-26.
 */
@WebServlet(name = "rankResponse",urlPatterns="/rankResponse",asyncSupported=false)
public class RankResponseServlet extends AbstractResponseHttpServlet {
    private static final long serialVersionUID = -335141463322209665L;
    private static Logger log = LoggerFactory.getLogger( RankResponseServlet.class );
    private static final String name = "rank";

    public RankResponseServlet( ) {
        super( name );
    }

    @Override
    public CrawResult setResult( HttpServletRequest request, Long request_id, String pageIndex,CrawRequest crawReq ) {
        RankCrawResult crawResult = new RankCrawResult();
        crawResult.setId( request_id );
        crawResult.setPageIndex( Integer.parseInt( pageIndex ) );
        log.info( "rank response id {},pageIndex{}",request_id,pageIndex );
        String numIid = request.getParameter( "num_iid" );
        String sourceType = request.getParameter( "sourceType" );
        List<RankItem> items = new ArrayList<>(  );
        if(numIid!=null){
            if("taobao".equals( sourceType ) || "tmall".equals( sourceType )){
                items = getItems( request, numIid );
            }else if("mTaobao".equals( sourceType ) ){
                items = getItemsByJsonp( request, numIid );
            }else{
                items = getItemsByJson( request, numIid );
            }
        }
        crawResult.setItems( items );
        return crawResult;
    }

    private List<RankItem> getItemsByJsonp( HttpServletRequest request,String numIid ) {
        String ip = request.getParameter( "client_ip" );
        log.info( "rank getItems : {},ip : {}",numIid,ip);
        List<RankItem> items = new ArrayList<>(  );
        String json = numIid.substring( numIid.indexOf( "{" ),numIid.lastIndexOf( "}" )+1 );
        try{
            JSONObject o = JSON.parseObject( json );
            if(o!=null){
                JSONArray listItem = o.getJSONArray( "listItem" );
                if(listItem!=null && listItem.size()>0){
                    for ( Object o1 : listItem ) {
                        JSONObject item = (JSONObject) o1;
                        RankItem ri = new RankItem();
                        ri.setNumIid( Long.parseLong( item.getString( "itemNumId" ) ) );
                        ri.setIp( ip );
                        items.add( ri );
                    }
                }
            }
        }catch ( Exception e ){
            write2File(json);
            e.printStackTrace();
            log.error( "json {}",e );
        }
        return items;
    }

    public void write2File( String json ){
//        try {
//            String fileName = System.currentTimeMillis()+".js";
//            FileWriter writer = new FileWriter( "C:/"+fileName );
//            writer.write( json );
//            writer.flush();
//            writer.close();
//        }catch ( Exception e ){
//            e.printStackTrace();
//        }
    }

    private List<RankItem> getItemsByJson( HttpServletRequest request,String numIid ) {
        String ip = request.getParameter( "client_ip" );
        log.info( "rank getItems : {},ip : {}",numIid,ip);
        List<RankItem> items = new ArrayList<>(  );
        try{
            JSONObject o = JSON.parseObject( numIid );
            if(o!=null){
                JSONArray srp = o.getJSONArray( "srp" );
                if(srp!=null && srp.size()>0){
                    for ( Object o1 : srp ) {
                        JSONObject item = (JSONObject) o1;
                        RankItem ri = new RankItem();
                        ri.setNumIid( item.getLong( "nid" ) );
                        ri.setIp( ip );
                        items.add( ri );
                    }
                }
            }
        }catch ( Exception e ){
            write2File(numIid);
            e.printStackTrace();
            log.error( "json {}",e );
        }
        return items;
    }

    private List<RankItem> getItems( HttpServletRequest request,String numIid ) {
        String ip = request.getParameter( "client_ip" );
        log.info( "rank getItems : {},ip : {}",numIid,ip);
        List<RankItem> items = new ArrayList<>(  );
        if( StringUtils.isNotEmpty( numIid )) {
            String[] idArray = numIid.split( "," );
            for ( int i = 0; i < idArray.length; i++ ) {
                Long id = Long.valueOf( idArray[i] );
                RankItem item = new RankItem();
                item.setNumIid( id );
                item.setIp( ip );
                items.add( item );

            }
        }
        return items;
    }
}
